package com.catmiw.csdn;

import java.util.Random;

public class EncryptionEngineTest {
	static Random rand=new Random();
	public static String encryptionEngine() {
		String strSrc = "12345678";
		String strKey = "Tom Lee";
		boolean bEncrypt = true;
		short nSrcLen;
		short nKeyLen;
		short nKeyPos;
		short nOffset;
		StringBuilder strDest=new StringBuilder("");
		String strOx = "0X";
		short nSrcPos;
		short nSrcAsc;
		short nTmpSrcAsc;
		short nRange;
		char[] sTmp = new char[255];
		String strParam = "";

		nSrcLen = (short) strSrc.length();
		if (((nSrcLen < 4) || (nSrcLen % 2 == 1)) && (bEncrypt == false))
			return ""; // 对于解密时长度小于4或者长度为奇数的直接返回空字符串

		nKeyLen = (short) strKey.length();
		if (nKeyLen > 0) {
			strKey = "Tom Lee";
			// strParam = get_paramValueString(db,0,0,BOSS_RUN,"",cErrorMsg);
			// strParam = get_locParamStr(BOSS_RUN) ;
			// if ( strParam == LOC_GANSU )
			// strKey = "Tom Lee";
			// if ( strParam == LOC_NEIMENG )
			// strKey = "NM Mobile";
			// }
			nKeyLen = (short) strKey.length();
			nKeyPos = -1;

			nRange = 256;

			if (bEncrypt) {
				//srand(time(0));
				//nOffset = rand() % nRange;
				nOffset=(short)rand.nextInt(nRange);
				String temp=Integer.toHexString(nOffset&0xff);
				temp="00".substring(temp.length())+temp;
				char[] tb=temp.toCharArray();
				System.arraycopy(tb, 0, sTmp, 0, tb.length);
				//sprintf(sTmp, "%1.2X", nOffset);
				System.out.println("[sTmp]="+new String(sTmp)+"\n");
//				printf("[sTmp]=%s\n", sTmp);
				strDest.append(temp);

				for (nSrcPos = 0; nSrcPos < nSrcLen; nSrcPos++) {
					nSrcAsc = (short) ((strSrc.charAt(nSrcPos) + nOffset) % 255);
					if (nKeyPos < nKeyLen-1)
						nKeyPos++;
					else
						nKeyPos = 0;
					nSrcAsc = (short) (nSrcAsc ^ strKey.charAt(nKeyPos));
					temp=Integer.toHexString(nSrcAsc&0xff);
					temp="00".substring(temp.length())+temp;
					//sprintf(sTmp, "%1.2X", nSrcAsc);
					strDest.append(temp);
					nOffset = nSrcAsc;
				}
			} 
			if (bEncrypt)
				return strDest.toString();
			else
				return strDest.toString();
		}
		return "123499999";
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String result = encryptionEngine();
		System.out.println(result);
	}

}
